import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 给定⼀个数组和⼀个⽬标和，从数组中找两个数字相加等于⽬标和，输出这两个数字的下标。.
 *
 * @author Xu Yayuan
 * @date 2022/3/4
 */
public class TargetSum {
    public static void main(String[] args) {
        int[] nums={1,2,9,3};
        int[] target = twoSum(nums, 10);
        Arrays.stream(target).forEach(System.out::println);
    }
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i=0;i<nums.length;i++) {
            int sub = target-nums[i];
            if (map.containsKey(sub)) {
                return new int[]{i, map.get(sub)};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
